/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package general;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;

/**
 *
 * @author foliveira
 */
public final class UDPMessage implements Message {

  private byte[] buffer;
  private DatagramPacket packet;
  private UDPConnection connection;

  public UDPMessage(UDPConnection connection) {
    
    this.connection = connection;
    buffer = new byte[1024];
    packet = new DatagramPacket(buffer, buffer.length);
    
  }

  public UDPMessage(UDPConnection connection, String text) {
    
    this.setText(text);
    this.connection = connection;    
    packet = new DatagramPacket(buffer, buffer.length);
    
  }

  public String getText() {
    return new String(buffer);
  }

  public void setText(String text) {
    this.buffer = text.getBytes();
  }

  @Override
  public String receive() throws Exception {
    
    connection.getSocket().receive(packet);
    String s = String.format("%s", new String(packet.getData()));
    return s;

  }

  
  @Override
  public void reply(String text) throws Exception {

      packet.setData(text.getBytes());
      connection.getSocket().send(packet);

  }

  @Override
  public void send(String text) throws Exception {
    reply(text);
  }

  public DatagramPacket getPacket() {
    if (packet != null) {
      return packet;
    } else {
      return null;
    }
  }

  public void setPacket(DatagramPacket packet) {
    this.packet = packet;
  }

  @Override
  public void to(String host, int port) throws Exception {
    this.packet.setAddress(InetAddress.getByName(host));
    this.packet.setPort(port);
  }
}
